const Router = require('@koa/router')
const router = new Router()

const md5 = require('md5')
const { getToken } = require('../tool/user')
const db = require('../db')
const { user: vriUser } = require('../vri')
const { sendAuthCode } = require('../tool/authcode')
const toolCode = require('../tool/code')
const uuid = require('uuid')

// 登陆
router.post('/login', async (ctx) => {
  const { body } = ctx.request
  const { adopt, error, value } = vriUser.login.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { username, password } = value
  const [user] = await db.find({
    form: 'user',
    field: ['id'],
    where: {
      username,
      password: md5(password),
    },
  })
  if (!user) {
    return (ctx.body = {
      code: 400,
      msg: '用户名或密码错误',
    })
  }
  const token = getToken(user)
  ctx.body = {
    code: 200,
    msg: '登陆成功',
    token,
  }
})

// 注册
router.post('/enroll', async (ctx) => {
  const { body } = ctx.request
  const { adopt, error, value } = vriUser.enroll.verifies(body, { mail: body.mail })
  if (!adopt) return ctx.error(430, { error: error.toString() })
  value.password = md5(value.password)
  const { mail, username, password } = value

  const sum = await db.count({
    form: 'user',
    where: {
      mail,
    },
  })
  if (sum)
    return (ctx.body = {
      code: 430,
      msg: '邮箱已注册',
    })
  const sun = await db.count({
    form: 'user',
    where: {
      username,
    },
  })
  if (sun)
    return (ctx.body = {
      code: 430,
      msg: '用户名已注册',
    })

  const { lastId: id } = await db.insert({
    value: { mail, username, password },
    form: 'user',
    lastId: true,
  })
  const token = getToken({ id })

  ctx.body = {
    code: 200,
    msg: '注册成功',
    token,
  }
})

// 验证用户名是否有效
router.get('/username', async (ctx) => {
  const { query } = ctx
  const { adopt, error, value } = vriUser.username.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { username } = value
  const sun = await db.count({
    form: 'user',
    where: {
      username,
    },
  })
  if (sun)
    return (ctx.body = {
      code: 430,
      msg: '用户名已注册',
    })

  ctx.body = {
    code: 200,
    msg: '用户名可以注册',
  }
})

// 验证码是否有效
router.post('/verifycode', async (ctx) => {
  const { body } = ctx.request
  const { adopt, error, value } = vriUser.verifycode.verifies(body, { mail: body.mail })
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { mail } = value

  const sum = await db.count({
    form: 'user',
    where: {
      mail,
    },
  })
  if (sum)
    return (ctx.body = {
      code: 430,
      msg: '邮箱已注册',
    })

  ctx.body = {
    code: 200,
    msg: '验证码有效',
  }
})

// 我的信息
router.get('/me', async (ctx, next) => {
  const user = ctx.state.user
  if (!user)
    return (ctx.body = {
      code: 401,
      msg: '登录状态失效或已过期',
    })
  ctx.body = {
    code: 200,
    user,
  }
})

// 发送验证码
router.get('/auth-code', async (ctx) => {
  const { query } = ctx
  const { value, error, adopt } = vriUser.authCode.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })

  const code = toolCode.add(value.mail)
  const info = await sendAuthCode(value.mail, code)
  if (info) {
    ctx.body = {
      msg: '已发送验证码',
      code: 200,
    }
  } else {
    throw '500'
  }
})

// 修改头像
router.post('/portrait', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = vriUser.portrait.verifies(body, { mail: body.mail })
  if (!adopt) return ctx.error(430, { error: error.toString() })
  await db.update({
    form: 'user',
    where: {
      id: user.id,
    },
    set: {
      portrait: value.portrait,
    },
  })
  ctx.body = {
    code: 200,
    msg: '修改成功',
  }
})

// 修改用户名
router.post('/modifyname', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = vriUser.modifyname.verifies(body, { mail: body.mail })
  if (!adopt) return ctx.error(430, { error: error.toString() })
  await db.update({
    form: 'user',
    where: {
      id: user.id,
    },
    set: {
      username: value.username,
    },
  })
  ctx.body = {
    code: 200,
    msg: '修改成功',
  }
})

// 用户列表
router.get('/list', async (ctx) => {
  const { query } = ctx
  const { adopt, error, value } = vriUser.search.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { qw, page, size } = value
  const where = {
    username: qw
      ? {
          op: 'LIKE',
          val: qw,
        }
      : undefined,
  }
  const data = await db.find({
    form: 'user',
    where,
    limit: page
      ? {
          page,
          size,
        }
      : undefined,
  })
  const total = await db.count({
    form: 'user',
    where,
  })
  ctx.body = {
    code: 200,
    data,
    total,
  }
})

// 修改权限
router.post('/power', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = vriUser.power.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { id } = value
  delete value.id
  const { affectedRows } = await db.update({
    form: 'user',
    where: {
      id,
    },
    set: value,
  })
  if (!affectedRows) return ctx.error(431)
  return (ctx.body = {
    code: 200,
    msg: '成功',
  })
})

/**获取该用户的店铺id */
async function myShop(userid) {
  const data = await db.first({
    form: 'shop',
    where: {
      userid,
    },
  })
  if (data) return data.id
}

async function myGoods(userid) {
  const sid = await myShop(userid)
  if (!sid)
    return (ctx.body = {
      code: 200,
      count: 0,
    })
  // 查询
  const cs = await db.find({
    form: 'commodity',
    field: ['id'],
    where: {
      shopid: sid,
      publish: 1,
    },
  })
  const cids = cs.map((e) => e.id)
  return cids
}

// 消息
router.get('/message', async (ctx) => {
  // 验证登陆
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { query } = ctx
  const { value, error, adopt } = vriUser.message.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const data = await db.find({
    form: 'comment',
    where: {
      commodityid: await myGoods(user.id),
    },
    limit: value,
    order: {
      createdAt: 'DESC',
    },
  })
  const total = await db.count({
    form: 'comment',
    where: {
      commodityid: await myGoods(user.id),
    },
    limit: value,
    order: {
      createdAt: 'DESC',
    },
  })
  ctx.body = {
    code: 200,
    data,
    total,
  }
})

// 未读消息数量
router.get('/unread-count', async (ctx) => {
  // 验证登陆
  const { user } = ctx.state
  if (!user) return ctx.error('401')

  const count = await db.count({
    form: 'comment',
    where: {
      commodityid: await myGoods(user.id),
      read: 0,
    },
    order: {
      createdAt: 'DESC',
    },
  })
  ctx.body = {
    code: 200,
    count,
  }
})

// 未读消息
router.get('/unread', async (ctx) => {
  // 验证登陆
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const data = await db.find({
    form: 'comment',
    where: {
      commodityid: await myGoods(user.id),
      read: 0,
    },
    order: {
      createdAt: 'DESC',
    },
  })
  ctx.body = {
    code: 200,
    data,
  }
})

// 标记为已读
router.post('/read', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { value, error, adopt } = vriUser.read.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { affectedRows } = await db.update({
    form: 'comment',
    where: {
      commodityid: await myGoods(user.id),
      id: value.ids,
      read: 0,
    },
    set: {
      read: 1,
    },
  })
  ctx.body = {
    code: 200,
    affectedRows,
  }
})

// 从id获取用户
router.get('/fromid', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { query } = ctx
  const { adopt, error, value } = vriUser.fromid.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const data = await db.first({
    form: 'user',
    where: {
      id: value.id,
    },
  })
  if (!data) return ctx.error(431)
  ctx.body = {
    code: 200,
    data,
  }
})
// 用户名违规
router.get('/report-name', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { query } = ctx
  const { adopt, error, value } = vriUser.fromid.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { id } = value
  delete value.id
  const { affectedRows } = await db.update({
    form: 'user',
    where: {
      id,
    },
    set: {
      username: '违规昵称' + uuid.v4().slice(0, 8),
    },
  })
  if (!affectedRows) return ctx.error(431)
  return (ctx.body = {
    code: 200,
    msg: '成功',
  })
})
// 头像违规
router.get('/report-portrait', async (ctx) => {
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { query } = ctx
  const { adopt, error, value } = vriUser.fromid.verifies(query)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { id } = value
  delete value.id
  const { affectedRows } = await db.update({
    form: 'user',
    where: {
      id,
    },
    set: {
      portrait: 'default.jpg',
    },
  })
  if (!affectedRows) return ctx.error(431)
  return (ctx.body = {
    code: 200,
    msg: '成功',
  })
})

module.exports = router.routes()
